import shareService from './share.js';
import permission from '../permission/index.js';
module.exports = {
	info: false,
	settingWritePhotosAlbum : false,
	start(){
		//关闭全屏模式
		//#ifdef APP-PLUS 
		plus.navigator.setFullscreen(false);
		plus.screen.lockOrientation("portrait-primary");
		// #endif
		let that = this;
		uni.getSystemInfo({
			success: function (res) {
				that.info = res;
				//console.log(this.info);
			}
		});
	},
	isIOS(){
		if (!this.info){
			this.info = uni.getSystemInfoSync();
		}
		return this.info && this.info.platform && this.info.platform=='ios';
	},
	isAndroid(){
		if (!this.info){
			this.info = uni.getSystemInfoSync();
		}
		return this.info && this.info.platform && this.info.platform=='android';
	},
	formatSize(){
		return new Promise((resolve, reject) => {
		//#ifdef APP-PLUS
			plus.cache.calculate((size) =>{//size是多少个字节单位是b
				let cacheSize = '';
				 //你可以做下面相应的处理
				if(size<1024){
					cacheSize=size+'B'; 
				}else if(size/1024>=1 && size/1024/1024<1){
					cacheSize= Math.floor(size/1024*100)/100+'KB';
				}else if(size/1024/1024>=1){
					cacheSize=Math.floor(size/1024/1024*100)/100+'M';
				}
				resolve(cacheSize);
			});
		//#endif 
		});

	},
	
	clearCache(){
		let that = this;
		uni.showModal({
			content: '确认要清空缓存吗？',
			success(res) {
				if (res.confirm) {
					that.doClearCache();
				}
			},
		});
	},
	doClearCache() {
		let that = this;
		//#ifdef APP-PLUS
		let os = plus.os.name;
		if (os == 'Android') {
			try{
				let main = plus.android.runtimeMainActivity();
				let sdRoot = main.getCacheDir();
				let files = plus.android.invoke(sdRoot, "listFiles");
				let len = files.length;
				for (let i = 0; i < len; i++) {
					let filePath = '' + files[i]; // 没有找到合适的方法获取路径，这样写可以转成文件路径  
					plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
						if (entry.isDirectory) {
							entry.removeRecursively(function(entry) { //递归删除其下的所有文件及子目录  
								uni.showToast({
									title: '缓存清理完成',
									duration: 2000
								});
								that.formatSize(); // 重新计算缓存  
							}, function(e) {
								console.log(e.message)
							});
						} else {
							entry.remove();
						}
					}, function(e) {
						console.log('文件路径读取失败')
					});
				}						
			}catch(e){
				plus.cache.clear(function() {
					uni.showToast({
						title: '缓存清理完成',
						duration: 2000
					});
					that.formatSize();
				});
			}
			
		} else { // ios  
			plus.cache.clear(function() {
				uni.showToast({
					title: '缓存清理完成',
					duration: 2000
				});
				that.formatSize();
			});
		}
		// #endif 
		// #ifdef MP
			plus.cache.clear(function() {
				uni.showToast({
					title: '缓存清理完成',
					duration: 2000
				});
				that.formatSize();
			});
		// #endif
	},
	copy(content,title=''){
		// #ifdef H5
		if (!document.queryCommandSupported('copy')) { //为了兼容有些浏览器 queryCommandSupported 的判断
			// 不支持
			uni.showToast({
				title: '浏览器不支持'
			});
		}
		let textarea = document.createElement("textarea")
		textarea.value = content
		textarea.readOnly = "readOnly"
		document.body.appendChild(textarea)
		textarea.select() // 选择对象
		textarea.setSelectionRange(0, content.length) //核心
		let result = document.execCommand("copy") // 执行浏览器复制命令
		if(result){
			uni.showToast({
				title: title+'复制成功',
				icon: 'none'
			});
		}else{
			uni.showToast({
				title: title+'无法复制！',
				icon: 'none'
			});
		}	
		textarea.remove();
		
		// #endif
		// #ifndef H5
		uni.setClipboardData({
			 data: content,
			 success: function() {
				 uni.showToast({
					title: title+'复制成功',
					icon: 'none'
				 });
			 }
		});
		// #endif
	 },

 
	 previewImage(urls) {
		if (typeof urls =='string'){
			urls=urls.split(',');
		}
		uni.previewImage({
			urls: urls,
			longPressActions: {
				itemList: ['发送给朋友', '保存图片', '收藏到微信'],
				success: function(data) {
					if (data.tapIndex==0 || data.tapIndex==2){
						let shareName=data.tapIndex==2?'收藏':'分享';
						shareService.image('发送图片',urls[data.index],data.tapIndex==2?'favorite':'friend').then((res) => {
							uni.showToast({
								title: shareName+'成功！',
								icon: 'none',
							})
						}).catch((err) => {
							uni.showToast({
								title: shareName+'失败！' ,
								icon: 'none',
							})
						
						});
					}else if (data.tapIndex==1){
						uni.saveImageToPhotosAlbum({
							filePath: urls[data.index],
							success: function() {
								console.log('保存成功');
								uni.showModal({
									title: '提示',
									content: '保存成功！',
									showCancel: false
								});
							},
							fail: function(e) {
								console.error(e);
								uni.showToast({
									title: '保存失败，请重试！',
									icon: 'none'
								})
							}
						});
					}
					console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
				},
				fail: function(err) {
					console.log(err.errMsg);
				}
			}
		});
	 },
	 // 保存图片
	 
	 saveImage(url) {
		return new Promise((resolve, reject) => {
			if (url) {
				permission.request('album').then(res=>{
					uni.showLoading({
						title: '正在下载'
					});
					if (url.toLowerCase().startsWith('http')){
						uni.downloadFile({
							url: url,
							success: data => {
								if (data.statusCode == 200) {
									uni.saveImageToPhotosAlbum({
										filePath: data.tempFilePath,
										success: (res) => {
											resolve(data.tempFilePath);
											uni.hideLoading();
											uni.showToast({
												title: '保存成功'
											});
										},
										fail(e) {
											reject({error_message:e.errMsg});
											uni.hideLoading();
											uni.showToast({
												title: '下载失败',
												icon: "none"
											});
										}
									});
								} else {
									reject({error_message:'下载失败，请检查网络和链接地址是否正确'});
									uni.hideLoading();
									uni.showToast({
										title: '下载失败，请检查网络和链接地址是否正确',
										icon: "none"
									});
								}
							},
							fail(e) {
								reject({error_message:e.errMsg});
								uni.hideLoading();
								uni.showToast({
									title: '下载失败，错误原因：' + e.errMsg,
									icon: "none"
								});
							}
						});
					}else{
						uni.saveImageToPhotosAlbum({
							filePath: url,
							success: () => {
								resolve(url);
								uni.hideLoading();
								uni.showToast({
									title: '保存成功'
								});
							},
							fail(e) {
								reject({error_message:e.errMsg});
								uni.hideLoading();
								uni.showToast({
									title: '下载失败',
									icon: "none"
								});
							}
						});
					}
				}).catch(res=>{
					
					reject({error_message:'暂无保存到相册的权限！'});
					uni.showModal({
						title: '提示',
						content: '暂无保存到相册的权限，是否进行设置？',
						confirmText: '立即开启',
						cancelText: '取消',
						success: data => {
							if (data.confirm) {
								permission.setting('album');
							}
						}
					});
				});
			}else{
				reject({error_message:'链接不正确'});
			}
		});		
	 }
	
}
